package babo.cd.physicalexperiment.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.TwoLevelHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.activity.EditDeviceActivity;
import babo.cd.physicalexperiment.bean.MyDevicesListBean;
import babo.cd.physicalexperiment.data.MyEnventData;
import babo.cd.physicalexperiment.databinding.FragmentShebeilistBinding;
import babo.cd.physicalexperiment.dialog.DialogCommon;
import babo.cd.physicalexperiment.utils.OKCallback;
import babo.cd.physicalexperiment.utils.OkUtils;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.URLS;
import babo.cd.physicalexperiment.view.RoundAngleImageView;

public class SheBeiFragmentListFragment extends BaseFragment {
    FragmentShebeilistBinding binding;
   int type=0;
   BaseQuickAdapter adapter;
   DialogCommon dialogCommon;
   List<MyDevicesListBean.MyDeviceInfo> datas=new ArrayList<>();
    @SuppressLint("ValidFragment")
   public SheBeiFragmentListFragment (int type){
       this.type=type;
   }
    @Override
    public View getLayout() {
        binding=FragmentShebeilistBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    public void initView() {
        binding.smr.setRefreshHeader(new TwoLevelHeader(getActivity()));
        binding.smr.setRefreshFooter(new ClassicsFooter(getActivity()));
        binding.smr.setEnableLoadMore(false);
        binding.smr.setEnableRefresh(true);
        binding.rcv.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter=new BaseQuickAdapter( R.layout.item_mydevice,datas) {
            @Override
            protected void convert(BaseViewHolder helper, Object item) {
          bindConvert(helper,(MyDevicesListBean.MyDeviceInfo) item);
            }


        };
        binding.rcv.setAdapter(adapter);
        Out.out("设置可以滑动AAA==");
    }

    private void bindConvert(BaseViewHolder helper, MyDevicesListBean.MyDeviceInfo item) {
        TextView txname=helper.getView(R.id.txname);
        TextView txstatus=helper.getView(R.id.txstatus);
        TextView tx_caozuo=helper.getView(R.id.tx_caozuo);
        TextView tx_bianji=helper.getView(R.id.tx_bianij);
        RoundAngleImageView ivhead=helper.getView(R.id.ivhead);
        tx_bianji.setOnClickListener(v -> {
            Intent intent=new Intent(getActivity(), EditDeviceActivity.class);
            intent.putExtra("data",item);
            startActivity(intent);
        });
        if (!TextUtils.isEmpty(item.getImg())){
            Glide.with(getActivity()).load(item.getImg()).into(ivhead);
        }else{
            Glide.with(getActivity()).load(R.mipmap.zhanwei).into(ivhead);
        }
        txname.setText(item.getName());

        int stuas=Integer.parseInt(item.getStatus());
        if (stuas==1){
            txstatus.setText("空闲");
            txstatus.setTextColor(getResources().getColor(R.color.stausfree));
            tx_caozuo.setVisibility(View.VISIBLE);
            tx_caozuo.setText("设置维护");
            tx_caozuo.setTextColor(Color.parseColor("#FFFFFF"));
            tx_caozuo.setBackgroundResource(R.drawable.backbtnblue);
        }else if (stuas==2){
            txstatus.setText("实验中");
            txstatus.setTextColor(getResources().getColor(R.color.statususing));
            tx_caozuo.setVisibility(View.GONE);
            tx_bianji.setVisibility(View.GONE);
        }else{
            txstatus.setText("维护中");
            txstatus.setTextColor(getResources().getColor(R.color.statusweihuzhong));
            tx_caozuo.setVisibility(View.VISIBLE);
            tx_caozuo.setText("恢复使用");
            tx_caozuo.setTextColor(getResources().getColor(R.color.blue));
            tx_caozuo.setBackgroundResource(R.drawable.backbtnbluekong);
        }

        tx_caozuo.setOnClickListener(v -> {
            dialogCommon=new DialogCommon(getActivity());
            dialogCommon.setTitle("提示");
            dialogCommon.setCancel("取消", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialogCommon.dismiss();
                }
            });
            if (stuas==1){
                String msg="是否要对<font color='#FF0000'>"+item.getName()+"</font>进行维护？维护期间，不能进行实验.";
                dialogCommon.setMessageHtml(msg);
                dialogCommon.show();
                dialogCommon.setConfirm("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                      doChangeStatus(item.getId(),"3",dialogCommon,item.getMac(),helper.getAdapterPosition());
                    }
                });

            } else if (stuas==3){
                String msg="是否要对<font color='#FF0000'>"+item.getName()+"</font>恢复使用？恢复后可正常进行实验。";
                dialogCommon.setMessageHtml(msg);
                dialogCommon.show();
                dialogCommon.setConfirm("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doChangeStatus(item.getId(),"1",dialogCommon,item.getMac(),helper.getAdapterPosition());
                    }
                });
            }

        });

    }

    private void doChangeStatus(String id, String sts, DialogCommon dialogCommon,String mac,int position) {
        LinkedHashMap hashMap=new LinkedHashMap();
        hashMap.put("id",id);
        hashMap.put("status",sts);
        hashMap.put("mac",mac);

        OkUtils.performByJsonArray(getActivity(),URLS.adddevice,hashMap,2,new OKCallback(getActivity()){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                dialogCommon.dismiss();
                Out.toast(getActivity(),"操作成功！");
                datas.get(position).setStatus(sts);
                adapter.notifyItemChanged(position);



            }

            @Override
            public void Eorror(int code) {
                super.Eorror(code);
                Out.toast(getActivity(),"服务器异常，请稍后再试！");

            }

        });
    }

    @Override
    public void initData() {
        Out.out("这里的flag==="+type);
        getSheBeiList();
    }

    private void getSheBeiList() {
        OkUtils.GetOk(URLS.getdevice+"?expId="+type,new OKCallback(getActivity()){
            @Override
            public void Sucess(String str) {

                super.Sucess(str);
                Gson gson=new Gson();
                try {
                   binding.smr.finishRefresh(300);
                }catch (Exception e){}
                MyDevicesListBean myDevicesListBean=gson.fromJson(str,MyDevicesListBean.class);
                datas.addAll(myDevicesListBean.getData());
                if (datas.size()>0){
                    binding.rcv.setVisibility(View.VISIBLE);
                    binding.txNodata.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                }else{
                    binding.rcv.setVisibility(View.GONE);
                    binding.txNodata.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    public void setListener() {
        binding.smr.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
             datas.clear();
             getSheBeiList();
            }
        });

    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(MyEnventData message) {
        String msg=message.message;
        if (msg.equals("adddevice")){
            datas.clear();
            getSheBeiList();
        }

    }
}
